<!--
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-05-09 10:25:14
 * @LastEditors: icymoon911 icymoon911@163.com
 * @LastEditTime: 2024-11-06 15:34:54
 * @FilePath: \ken147258.topayClient\src\views\other\order-management\deal-list.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container" v-loading="loading">
    <div class="search-container">
      <FormList :initForm="initSearchForm" v-model:formModel="searchForm"></FormList>
    </div>
    <el-card shadow="never" class="table-container">
      <template #header>
        <div flex justify-end flex-items-center>
          <el-button
            type="primary"
            @click="handleTableBtnClick({}, 'monitoring-broadcast')"
            >监控播报设置</el-button
          >
          <el-button type="primary" @click="handleTableBtnClick({}, 'set-groups-send')"
            >发送消息群组设置</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <div line-height-32px>是否需要人工审核：</div>
          <el-switch
            inline-prompt
            v-model="isAudit"
            active-text="无需审核"
            inactive-text="需要审核"
            @change="handleChangeAuditStatus"
          ></el-switch>
          <!-- <el-text float-right line-height-32px class="mx-1 !mr-[20px]" type="info">更新倒计时：{{
          timeLog
        }}</el-text> -->
        </div>
        <!-- <el-button type="primary" @click="handleQuery()"
          ><i-ep-refresh />刷新订单</el-button
        > -->
      </template>
      <comTable
        :data="tableDatasCom"
        :config="tableconfig"
        :tableHeader="tableHeader"
        @link-click="handleTableBtnClick"
      >
        <template #look-img="{ row, index }">
          <template v-if="row.type === 2">
            <el-button
              type="primary"
              size="small"
              h-22px
              line-height-22px
              pl-5px
              pr-5px
              @click="handleTableBtnClick(row, 'look-img')"
            >
              查看图片
            </el-button>
          </template>
          <template v-else>-</template>
        </template>
      </comTable>

      <pagination
        v-if="tableDatasObj.paging.total > 0"
        v-model:total="tableDatasObj.paging.total"
        v-model:page="tableDatasObj.paging.page"
        v-model:limit="tableDatasObj.paging.limit"
        @pagination="handleQuery"
      />
    </el-card>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="dialog.closeDialog"
      @closed="dialog.closedDialog"
    >
      <FormList
        v-if="initDialogForm.initKeys.length"
        v-model:formRef="formDialogId"
        v-model:formModel="formDialogModel"
        :initForm="initDialogForm"
      ></FormList>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="dialog.leftBtnText"
            type="primary"
            @click="dialog.handleLeftClick"
            >{{ dialog.leftBtnText }}</el-button
          >
          <el-button v-if="dialog.rightBtnText" @click="dialog.handleRightClick">{{
            dialog.rightBtnText
          }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { watch, inject } from "vue";
import { FormInstance } from "element-plus";
import {
  list,
  add,
  dels,
  update as edit,
  autoSend,
  getGroups,
  sendMsg,
  getFileUrlById,
} from "@/api/tg_msg";
import { updates as groupUpdates } from "@/api/tg_group_log";
import { upsert_address, dels_address, getlist_address } from "@/api/bot_watch";
import { list as configList, update as configEdit } from "@/api/config";
import { usePayProductStore } from "@/store";
import { cloneDeep, multiply } from "lodash";

const getFormatDate = inject("getFormatDate");
const getTimestamp = inject("getTimestamp");
const tableDatasObj = ref({
  list: [],
  paging: {
    limit: 20,
    page: 1,
    total: 0,
  },
  queryParams: {},
});
const loading = ref(false);

const options = {
  is_public: [
    { label: "未发布", value: "1" },
    { label: "已发布", value: "2" },
  ],
  type: [
    { label: "文本", value: "1" },
    { label: "图片", value: "2" },
  ],
};

const searchForm = ref({});
const initSearchForm = ref({
  // 表单标签位置
  // labelPosition: "right",
  formAttrs: {
    // 是否内联
    inline: true,
  },
  rowAttrs: {
    // 行内表单数量
    columnsNum: 4,
  },
  // 初始化表单字段
  initKeys: [
    {
      // 类型
      type: "input",
      // 唯一标识
      key: "tg_username",
      // 表单属性
      formAttrs: {
        label: "用户名",
      },
      // 控制属性
      controlAttrs: {
        // 提示文本
        placeholder: "请输入tg用户名",
        // 是否可清空
        clearable: true,
      },
      // 控制事件
      controlOn: {},
    },
    {
      // 类型
      type: "input",
      // 唯一标识
      key: "msg",
      // 表单属性
      formAttrs: {
        label: "内容",
      },
      // 控制属性
      controlAttrs: {
        // 提示文本
        placeholder: "请输入内容",
        // 是否可清空
        clearable: true,
      },
      // 控制事件
      controlOn: {},
    },
    {
      // 类型
      type: "select",
      // 唯一标识
      key: "is_public",
      // 表单属性
      formAttrs: {
        label: "发布状态",
      },
      // 控制属性
      controlAttrs: {
        // 提示文本
        placeholder: "请选择发布状态",
        // 是否可清空
        clearable: true,
        options: options.is_public,
      },
      // 控制事件
      controlOn: {},
    },
    {
      // 类型
      type: "buttons",
      // 按钮
      btns: [
        {
          // 文本
          text: "搜索",
          // 控制属性
          controlAttrs: {
            // 类型
            type: "primary",
            icon: "search",
          },
          // 控制事件
          controlOn: {
            // 点击
            click: (e: Event, formRef: FormInstance, data: object) => {
              formRef.validate((valid) => {
                if (valid) {
                  console.log("fields", data);
                  tableDatasObj.value.paging.page = 1;

                  let tempData = { ...data };

                  data.min_amount_max_amount = data.min_amount_max_amount || [];
                  tempData.min_amount = data.min_amount_max_amount[0];
                  tempData.max_amount = data.min_amount_max_amount[1];

                  delete tempData.min_amount_max_amount;

                  tableDatasObj.value.queryParams = tempData;

                  handleQuery(tableDatasObj.value.paging);
                }
              });
            },
          },
        },
        {
          // 文本
          text: "重置",
          // 控制属性
          controlAttrs: {
            icon: "refresh",
          },
          // 控制事件
          controlOn: {
            // 点击
            click: resetQuery,
          },
        },
      ],
    },
  ],
});

/** 重置查询 */
function resetQuery(e: Event, formRef: FormInstance, data: object) {
  // 重置表单
  formRef.resetFields();
  // formRef.resetFields();
  // 查询
  tableDatasObj.value.paging.page = 1;
  tableDatasObj.value.paging.limit = 20;
  tableDatasObj.value.queryParams = { ...searchForm.value };
  const params = {
    ...tableDatasObj.value.queryParams,
    ...data,
    ...tableDatasObj.value.paging,
  };

  handleQuery(params);
}

// 表*********************************************
const tableDatasCom = computed(() => {
  return tableDatasObj.value.list.map((item: ProductListVO) => {
    // const return_statusCom = options.return_status.find(
    //   (tItem) => tItem.value.toString() === item.return_status.toString()
    // )?.label;

    return {
      ...item,
      createtimeCom: getFormatDate(item.createtime),
      is_publicCom:
        options.is_public.find(
          (tItem) => tItem.value.toString() === item.is_public.toString()
        )?.label + (item.auto_send_interval ? "(自动发送)" : ""),
      typeCom: options.type.find(
        (tItem) => tItem.value.toString() === item.type.toString()
      )?.label,
    };
  });
});
const tableconfig = {
  // tableHeight: 480, //表格高度
  isSelection: false, //显示复选框
  isRowClick: false, //使用行点击
  isStripe: true, //隐藏斑马纹，与背景色不可同时用
  isShowSummary: false, //显示共计
  isIndex: true, //自定义序号
  isNeedPagination: true, //是否需要分页
};
const tableHeader = [
  { label: "ID", prop: "id", width: 200 },
  { label: "用户名", prop: "username", width: 200 },
  { label: "发布状态", prop: "is_publicCom", width: 200 },
  { label: "内容", prop: "msg", minWidth: 200 },
  { label: "消息类型", prop: "typeCom", width: 120 },
  { label: "查看图片", prop: "look-img", width: 200, type: "slot" },
  { label: "创建时间", prop: "createtimeCom", width: 200 },
  {
    label: "操作",
    isSort: false,
    prop: "operation",
    columnAttrs: {
      fixed: "right",
      width: "200",
    },
    children: [
      {
        type: "button",
        btnText: "审核",
        title: "edit",
        controlAttrsFunc: (obj) => {
          let result = {};

          if (obj.is_public.toString() === "1") {
          } else {
            if (!result.style) {
              result.style = {};
            }
            result.style.display = "none";
          }

          return result;
        },
      },
      {
        type: "button",
        btnText: "发送",
        title: "send",
        controlAttrsFunc: (obj) => {
          let result = {};

          if (obj.is_public.toString() === "2") {
          } else {
            if (!result.style) {
              result.style = {};
            }
            result.style.display = "none";
          }

          return result;
        },
      },
      {
        type: "button",
        btnText: "自动发送",
        title: "auto-send",
        controlAttrsFunc: (obj) => {
          let result = {};

          if (obj.is_public.toString() === "2") {
          } else {
            if (!result.style) {
              result.style = {};
            }
            result.style.display = "none";
          }

          return result;
        },
      },
      {
        type: "button",
        btnText: "删除",
        title: "del",
      },
    ],
  },
];

/**
 * 查询
 */
function handleQuery(paging: { page: number; limit: number }) {
  loading.value = true;
  list({ ...tableDatasObj.value.paging, ...tableDatasObj.value.queryParams })
    .then((res) => {
      tableDatasObj.value.list = res.list;
      tableDatasObj.value.paging.total = res.total;

      // options.status = Object.keys(res.statusName).map((key) => ({
      //   label: res.statusName[key],
      //   value: key,
      // }));

      Object.keys(options).map((key) => {
        const item = initSearchForm.value.initKeys;
        const i = item.findIndex((item) => item.key === key);

        if (i > -1) {
          const control = initSearchForm.value.initKeys[i].controlAttrs;
          if (!(control.options && control.options.length)) {
            initSearchForm.value.initKeys[i].controlAttrs.options = options[key];
          }
        }
      });
    })
    .finally(() => {
      loading.value = false;
    });

  // loadstat();
  // if (tableDatasObj.paging.typeCode) {
  // loading.value = true;
  // getDictPage(queryParams)
  //   .then(({ data }) => {
  //     dictList.value = data.list;
  //     total.value = data.total;
  //   })
  //   .finally(() => (loading.value = false));
  // }
}

const initDialogForm = ref({
  // 表单标签位置
  formAttrs: {
    // 是否内联
    // inline: true,
    labelPosition: "top",
  },
  rowAttrs: {
    // 行内表单数量
    columnsNum: 1,
  },
  // 初始化表单字段
  initKeys: <any>[],
});

let initDialogFormBak = cloneDeep(initDialogForm.value);

const isHasOptions = [
  {
    // 标签
    label: "关闭",
    // 值
    value: 0,
  },
  {
    // 标签
    label: "开启",
    // 值
    value: 1,
  },
];

function handleTableBtnClick(row: object, title: string) {
  dialog.type = title;
  dialog.visible = true;
  dialog.singleData = tableDatasObj.value.list.find((item) => item.id === row.id);

  if (title === "add") {
    // 新增支付产品
    dialog.title = "新增";
    dialog.leftBtnText = "确 定";
    dialog.rightBtnText = "取 消";

    initDialogForm.value.initKeys = [
      {
        // 类型
        type: "input",
        // 唯一标识
        key: "username",
        // 表单属性
        formAttrs: {
          label: "用户名",
        },
        // 控制属性
        controlAttrs: {
          // 提示文本
          placeholder: "请输入用户名",
          // 是否可清空
          clearable: true,
        },
        // 控制事件
        controlOn: {},
      },
      {
        // 类型
        type: "input",
        // 唯一标识
        key: "pwd",
        // 表单属性
        formAttrs: {
          label: "密码",
        },
        // 控制属性
        controlAttrs: {
          // 提示文本
          placeholder: "请输入密码",
          // 是否可清空
          clearable: true,
        },
        // 控制事件
        controlOn: {},
      },
    ];
  } else if (title === "send") {
    dialog.visible = true;
    dialog.title = "发送消息";
    dialog.leftBtnText = "发 送";
    dialog.rightBtnText = "取 消";
    dialog.width = 700;

    initDialogForm.value.rowAttrs.columnsNum = 1;

    getGroups({ type: "group" }).then((res) => {
      let list = res.list.map((item) => ({
        key: item.id,
        label: item.group_name,
        checked: item.is_send === 1,
      }));

      let checkedValus = (list.filter((item) => item.checked) || []).map(
        (item) => item.key
      );

      initDialogForm.value.initKeys = [
        {
          // 类型
          type: "transfer",
          // 唯一标识
          key: "groupIds",
          // 表单属性
          formAttrs: {
            label: "机器人加入的群组",
          },
          // 控制属性
          controlAttrs: {
            titles: ["未选择群组", "已选择群组"],
            style: {
              textAlign: "center",
            },
            data: list,
          },
          // 控制事件
          controlOn: {},
          value: checkedValus,
        },
      ];
    });
  } else if (title === "auto-send") {
    dialog.visible = true;
    dialog.title = "自动发送";
    dialog.leftBtnText = "确 定";
    dialog.rightBtnText = "取 消";
    dialog.width = 340;

    initDialogForm.value.rowAttrs.columnsNum = 1;

    initDialogForm.value.initKeys = [
      {
        // 类型
        type: "switch",
        // 唯一标识
        key: "isAutoSend",
        // 表单属性
        formAttrs: {
          label: "是否自动发送",
        },
        // 控制属性
        controlAttrs: {
          inlinePrompt: true,
          activeText: "是",
          inactiveText: "否",
        },
        // 控制事件
        controlOn: {
          change(val) {
            initDialogForm.value.initKeys[1].controlAttrs.disabled = !val;
            initDialogForm.value.initKeys[0].value = val;

            if (val) {
              if (!initDialogForm.value.initKeys[1].value) {
                initDialogForm.value.initKeys[1].value = 1;
              }
            }
          },
        },
        value: !!dialog.singleData.auto_send_interval,
      },
      {
        // 类型
        type: "input-number",
        // 唯一标识
        key: "auto_send_interval",
        // 表单属性
        formAttrs: {
          label: "时间间隔（小时）",
        },
        // 控制属性
        controlAttrs: {
          disabled: !dialog.singleData.auto_send_interval,
          min: 1,
        },
        // 控制事件
        controlOn: {},
        value: dialog.singleData.auto_send_interval,
      },
    ];
  } else if (title === "edit") {
    dialog.visible = true;
    dialog.title = "审核";
    dialog.leftBtnText = "发 布";
    dialog.rightBtnText = "取 消";
    // dialog.width = 400;

    // initDialogForm.value.rowAttrs.columnsNum = 1;

    // password 密码（6-18位）
    // mobile 手机号
    // email 邮箱
    // safety_code 安全码
    // status 状态(1:启用；2:禁用)

    initDialogForm.value.initKeys = [
      {
        // 类型
        type: "input",
        // 唯一标识
        key: "username",
        // 表单属性
        formAttrs: {
          label: "用户名",
        },
        // 控制属性
        controlAttrs: {
          // 提示文本
          placeholder: "请输入用户名",
          // 是否可清空
          clearable: true,
          readonly: true,
        },
        // 控制事件
        controlOn: {},
        value: dialog.singleData.username,
      },
      {
        // 类型
        type: "textarea",
        // 唯一标识
        key: "msg",
        // 表单属性
        formAttrs: {
          label: "内容",
        },
        // 控制属性
        controlAttrs: {
          // 提示文本
          placeholder: "请查看内容",
          // 是否可清空
          clearable: true,
        },
        // 控制事件
        controlOn: {},
        value: dialog.singleData.msg,
      },
    ];
  } else if (title === "del") {
    // 删除
    dialog.visible = false;

    ElMessageBox.confirm("确定要删除这条消息吗？", "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      // 访问接口；刷新列表
      let params = { ids: row.id };
      dels(params).then(() => {
        ElMessage.success("删除成功");

        if (tableDatasObj.value.list.length === 1) {
          if (tableDatasObj.value.paging.page > 1) {
            --tableDatasObj.value.paging.page;
          }
        }

        handleQuery();
      });
    });
  } else if (title === "look-img") {
    dialog.visible = false;

    const fileIds = row.append.split(",");
    let params = { id: fileIds[fileIds.length - 1] };
    getFileUrlById(params).then((res) => {
      ElMessageBox({
        title: "查看图片",
        center: true,
        showConfirmButton: false,
        message: h(ElImage, {
          src: res,
          fit: "contain",
          style: {
            width: "420px",
          },
        }),
      });
    });
  } else if (title === "set-groups-send") {
    dialog.visible = true;
    dialog.title = "发送消息群组设置";
    dialog.leftBtnText = "发 送";
    dialog.rightBtnText = "取 消";
    dialog.width = 700;

    initDialogForm.value.rowAttrs.columnsNum = 1;

    getGroups({ type: "group" }).then((res) => {
      let list = res.list.map((item) => ({
        key: item.id,
        label: item.group_name,
        checked: item.is_send === 1,
      }));

      let checkedValus = (list.filter((item) => item.checked) || []).map(
        (item) => item.key
      );

      dialog.singData = res.list;

      initDialogForm.value.initKeys = [
        {
          // 类型
          type: "transfer",
          // 唯一标识
          key: "groupIds",
          // 表单属性
          formAttrs: {
            label: "机器人加入的群组",
          },
          // 控制属性
          controlAttrs: {
            titles: ["未选择群组", "已选择群组"],
            style: {
              textAlign: "center",
            },
            data: list,
          },
          // 控制事件
          controlOn: {},
          value: checkedValus,
        },
      ];
    });
  } else if (title === "monitoring-broadcast") {
    dialog.visible = true;
    dialog.title = "监控播报设置";
    dialog.leftBtnText = "确 认";
    dialog.rightBtnText = "取 消";
    dialog.width = 700;

    initDialogForm.value.rowAttrs.columnsNum = 1;

    (async () => {
      const addressAndGroupPromise = [
        getlist_address(),
        getGroups({ type: "group" }),
      ].map(async (item, i) => {
        const res = await item;

        return res;
      });

      const addressse = (await addressAndGroupPromise[0]) || [];
      const groups = await addressAndGroupPromise[1];

      let list = groups.list.map((item) => ({
        value: item.id,
        label: item.group_name,
        // checked: false,
      }));

      addressse.map((item) => {
        item.disabled = !!item.disabled; // 是否禁用
        item.children = list;
      });

      let modelVal = [];
      addressse
        .filter((item) => item.groupids.length)
        .map((item) => {
          item.groupids
            .filter((gid) => gid.trim())
            .map((gid) => {
              modelVal.push([item.address, gid]);
            });
        });

      dialog.singData = addressse;

      const isLookFunc = (val) => {
        addressse.map((item) => {
          item.disabled = !val;
        });

        initDialogForm.value.initKeys.map((item, i) => {
          if (i !== 0) {
            if (item.type === "cascader-panel") {
              const options = initDialogForm.value.initKeys[i].controlAttrs.options.map(
                (item) => {
                  return {
                    ...item,
                    disabled: !val,
                  };
                }
              );

              initDialogForm.value.initKeys[i].controlAttrs.options = options;
            } else {
              initDialogForm.value.initKeys[i].controlAttrs.disabled = !val;
            }
          }
        });
      };

      initDialogForm.value.initKeys = [
        {
          // 类型
          type: "switch",
          // 唯一标识
          key: "isBroadcast",
          // 表单属性
          formAttrs: {
            label: "是否播报",
          },
          // 控制属性
          controlAttrs: {},
          // 控制事件
          controlOn: {
            change(val) {
              isLookFunc(val);

              initDialogForm.value.initKeys[0].value = val;
            },
          },
          value: !addressse[0]?.disabled,
        },
        {
          // 类型
          type: "auto-input",
          // 唯一标识
          key: "address",
          // 表单属性
          formAttrs: {
            label: "外链地址",
          },
          // 控制属性
          controlAttrs: {
            placeholder: "请输入外链地址",
            loadAll: addressse.map((item) => ({
              value: item.address,
              remark: item.name,
            })),
            btns: [],
          },
          // 控制事件
          controlOn: {
            customerInput: (val: string) => {
              const valTrim = val.trim();

              if (valTrim) {
                if (addressse.some((item) => item.address === valTrim)) {
                  // 出现删除按钮
                  initDialogForm.value.initKeys[1].btns = [
                    {
                      text: "删除",
                      controlAttrs: {
                        icon: "delete",
                        type: "danger",
                      },
                      controlOn: {
                        click: (e) => {
                          ElMessageBox.confirm("确定要删除这条外链地址吗？", "提示", {
                            confirmButtonText: "确定",
                            cancelButtonText: "取消",
                            type: "warning",
                          }).then(() => {
                            dels_address({ address: valTrim }).then((res) => {
                              ElMessage.success("删除成功");

                              handleTableBtnClick(row, "monitoring-broadcast");
                            });
                          });
                        },
                      },
                    },
                  ];
                } else {
                  // 出现添加按钮
                  initDialogForm.value.initKeys[1].btns = [
                    {
                      text: "添加",
                      controlAttrs: {
                        icon: "plus",
                        type: "primary",
                      },
                      controlOn: {
                        click: (e) => {
                          if (valTrim.length > 40) {
                            ElMessage.error("外链地址太长了，请检查外链地址是否正确");
                            return;
                          }
                          
                          upsert_address({ params: { address: valTrim } }).then((res) => {
                            ElMessage.success("添加成功");

                            handleTableBtnClick(row, "monitoring-broadcast");
                          });
                        },
                      },
                    },
                  ];
                }
              }
            },
          },
          // value: checkedValus,
        },
        // {
        //   // 别名
        //   type: "input",
        //   // 唯一标识
        //   key: "name",
        //   // 表单属性
        //   formAttrs: {
        //     label: "别名",
        //   },
        //   // 控制属性
        //   controlAttrs: {},
        //   // 控制事件
        //   controlOn: {},
        //   // value: checkedValus,
        // },
        {
          // 类型
          type: "cascader-panel",
          // 唯一标识
          key: "setting",
          // 表单属性
          formAttrs: {
            label: "地址设置",
          },
          // 控制属性
          controlAttrs: {
            props: {
              multiple: true,
            },
            options: addressse.map((item) => ({
              ...item,
              label: item.address,
              value: item.address,
            })),
          },
          // 控制事件
          controlOn: {},
          value: modelVal,
        },
      ];

      isLookFunc(!addressse[0]?.disabled); // 是否禁用
    })();
  }
}

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 450,
  title: "",
  leftBtnText: "确 定",
  rightBtnText: "取 消",
  singData: {},
  closeDialog() {
    dialog.visible = false;
  },
  closedDialog() {
    formDialogId.value = {};
    formDialogModel.value = {};
    initDialogForm.value.initKeys.splice(0);
    Object.keys(dialogBak).map((key) => {
      dialog[key] = dialogBak[key];
    });

    initDialogForm.value = cloneDeep(initDialogFormBak);
  },
  handleLeftClick() {
    if (dialog.type === "add") {
      formDialogId.value.validate((valid, fields) => {
        if (valid) {
          let params = { ...formDialogModel.value };

          add(params).then((res) => {
            ElMessage.success("添加成功");
            dialog.closeDialog();
            handleQuery();
          });
        }
      });
    } else if (dialog.type === "send") {
      formDialogId.value.validate((valid, fields) => {
        if (valid) {
          let photo = null;

          if (dialog.singleData.type === 2) {
            photo = dialog.singleData.append.split(",");

            photo = photo[photo.length - 1];
          }

          let params = {
            ...formDialogModel.value,
            text: dialog.singleData.msg,
            tg_user_id: dialog.singleData.tg_user_id,
            photo,
          };

          edit({
            id: dialog.singleData.id,
            group_ids: formDialogModel.value.groupIds.join(","),
          }).then(() => {
            sendMsg(params).then((res) => {
              ElMessage.success("推送消息成功");
              dialog.closeDialog();
              handleQuery();
            });
          });
        }
      });
    } else if (dialog.type === "auto-send") {
      formDialogId.value.validate((valid, fields) => {
        if (valid) {
          console.log(initDialogForm.value.initKeys[0].value);
          console.log(formDialogModel.value);

          let params = {
            auto_send_interval: formDialogModel.value.auto_send_interval,
            id: dialog.singleData.id,
          };

          if (!formDialogModel.value.isAutoSend) {
            params.auto_send_interval = 0;
          }

          autoSend(params).then((res) => {
            ElMessage.success("设置成功");
            dialog.closeDialog();
            handleQuery();
          });
        }
      });
    } else if (dialog.type === "edit") {
      formDialogId.value.validate((valid, fields) => {
        if (valid) {
          let params = {
            id: dialog.singleData.id,
            is_public: 2,
            msg: formDialogModel.value.msg,
          };

          edit(params).then((res) => {
            ElMessage.success("发布成功");
            const id = dialog.singleData.id;
            dialog.closeDialog();
            handleQuery();

            setTimeout(() => {
              ElMessageBox.confirm("该消息已能群发，是否发送呢？", "发送消息", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                handleTableBtnClick({ id }, "send");
              });
            }, 1000);
          });
        }
      });
    } else if (dialog.type === "set-groups-send") {
      formDialogId.value.validate((valid, fields) => {
        if (valid) {
          let params = {
            datas: dialog.singData.map((item) => ({
              ...item,
              is_send: formDialogModel.value.groupIds.includes(item.id) ? 1 : 2,
            })),
          };

          groupUpdates(params).then((res) => {
            ElMessage.success("修改成功");
            dialog.closeDialog();
          });
        }
      });
    } else if (dialog.type === "monitoring-broadcast") {
      formDialogId.value.validate((valid, fields) => {
        console.log("formDialogModel.value=", formDialogModel.value);
        if (valid) {
          let params = dialog.singData.map((item) => ({
            address: item.address,
            disabled: initDialogForm.value.initKeys[0].value ? 0 : 1,
            groupids: (formDialogModel.value.setting || [])
              .filter((arr) => arr[0] === item.address)
              .map((arr) => arr[1]),
          }));

          upsert_address({ params }).then((res) => {
            ElMessage.success("修改成功");
            dialog.closeDialog();
          });
        }
      });
    }
  },
  handleRightClick() {
    dialog.closeDialog();
  },
});
const dialogBak = { ...dialog };

let formDialogId = ref<FormInstance>();

let formDialogModel = ref({});

let isAudit = ref(false);

let configData = {};

function handleQueryConfig(func) {
  configList({}).then((res) => {
    configData = res.list.find((item) => item.name === "is_text_audit");

    func && func();
  });
}

handleQueryConfig(() => {
  isAudit.value = configData.val === "1";
});

function handleChangeAuditStatus(val) {
  configData.val = val ? "1" : "2";

  loading.value = true;
  configEdit(configData)
    .then((res) => {
      ElMessage.success("修改成功");
      isAudit.value = configData.val === "1";
    })
    .catch(() => {
      isAudit.value = val;
      nextTick(() => {
        isAudit.value = val;
      });
    })
    .finally(() => {
      loading.value = false;
    });
}

onMounted(() => {
  tableDatasObj.value.queryParams = { ...searchForm.value };

  handleQuery(tableDatasObj.value.paging);

  // handleAutoRefreshChange(true);
});
</script>

<style lang="scss" scoped>
.info-container {
  font-size: var(--el-font-size-extra-small);

  span {
    background-color: #1e9fff;
    display: inline-block;
    padding: 0 10px;
    margin: 0 5px;
    color: #fff;
  }
}
</style>
